-- ngx.say("dy_up")

local mp = require ('MessagePack')

local upserver = ngx.shared.upserver
local cjson = require("cjson")
local random = require('math').random
local randomseed = require('math').randomseed

local function _log(str) ngx.log(ngx.ERR, str) end

local getServerByType = function (typeName, servers)
  _log("typeName =" .. typeName)
  if 'table' ~= type(servers)  then
    _log("getServerByType server not table")
    return nil
  end

  if typeName == nil then
    _log("getServerByType nil " .. typeName)
    return nil
  end

  local list = servers[typeName]
  if not list then
    _log("getServerByType list nil")
    return nil
  end

  local len = table.getn(list)
  _log("len[" ..typeName .. "]=" .. len)
  randomseed(os.time())
  local targetServer = list[random(len)]
  -- _log("targetServer = " .. targetServer)
  return targetServer

end

local servers = upserver:get('servers')
if not servers then
  _log("servers not ready")
  return ngx.say("servers not ready")
end
servers = mp.unpack(servers)
local str_servers = cjson.encode(servers)
_log(str_servers)
-- ngx.say(str_servers)

-- get /type
_log("ngx.var.request_uri=" .. ngx.var.request_uri)
_log("ngx.var.host=" .. ngx.var.host)

local typeName, newUri = string.match(ngx.var.request_uri, '/(.-)/(.*)')
newUri = '/' .. newUri
_log("typeName=" .. typeName)
_log("newUri=" .. newUri)

-- ngx.say("typeName=" , typeName)
local targetServer = getServerByType(typeName, servers)

if nil == targetServer then
  -- TODO code 503
  ngx.say("nil upstream server")
  return
end
_log("targetServer="..targetServer)

--创建http客户端实例
local http = require("resty.http")
local httpc = http.new()
local opt = {
  path = newUri,
  method = ngx.req.get_method(),
  headers = ngx.req.get_headers(),
  body = ngx.var.request_body
}
local resp, err = httpc:request_uri(targetServer, opt)

if not resp then
  ngx.say("request error :", err)
  return
end

--获取状态码
ngx.status = resp.status

--获取响应头
for k, v in pairs(resp.headers) do
  if k ~= "Transfer-Encoding" and k ~= "Connection" then
    ngx.header[k] = v
  end
end
ngx.header["bla"]="goo"
--响应体
ngx.say(resp.body)

httpc:close()


